/**
 * 
 */
package com.effectivsocial.service.impl;

import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.effectivsocial.domain.LinkGroup;
import com.effectivsocial.domain.ViewDefinition;
import com.effectivsocial.repository.LinkGroupRepository;
import com.effectivsocial.repository.ViewDefinitionRepository;
import com.effectivsocial.service.api.AbstractService;
import com.effectivsocial.service.api.ViewDefinitionService;

/**
 * @author Dhrubo
 * 
 */
@Named
@Slf4j

public class ViewDefinitionServiceImpl extends
		AbstractService<ViewDefinition, String> implements
		ViewDefinitionService {

	@Inject
	private ViewDefinitionRepository repository;
	
	@Inject
	private LinkGroupRepository linkGroupRepository;

	@Override
	protected void initInternal() {
		setRepository(repository);
	}

	public List<ViewDefinition> findAll() {
		return repository.findAll();
	}

	public ViewDefinition findByName(String name) {
		return repository.findByName(name);
	}
	
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void appendLinkGroup(String viewName, String linkGroup) {
		log.info("View Name = {}", viewName);
		log.info("Link Group = {}" , linkGroup);
		
		LinkGroup linkGrp = linkGroupRepository.findOne(linkGroup);
		
		
		ViewDefinition viewDefinition = repository.findByName(viewName);
		List<LinkGroup> existing = viewDefinition.getLinkGroups();
		
		if(existing == null) {
			List<LinkGroup> linkGroups = new ArrayList<LinkGroup>();
			linkGroups.add(linkGrp);
			viewDefinition.setLinkGroups(linkGroups);
		}
		else{
			existing.add(linkGrp);
		}
		
	}
	@Transactional(propagation=Propagation.REQUIRED)
	public void deleteAllAssociatedLinkGroups() {
		//first get all and delete the associations
		List<ViewDefinition> viewDefinitions = repository.findAll();
		
		for(ViewDefinition viewDefinition : viewDefinitions) {
			List<LinkGroup> linkGroups = viewDefinition.getLinkGroups();
			viewDefinition.setLinkGroups(null);			
		}
		
		
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void purgeAll() {
		repository.deleteAllInBatch();
		
	}

}
